<script lang="ts" setup>
import { useTemplateRef, onMounted, watch } from 'vue';
import { useElementVisibility, watchPausable } from '@vueuse/core';

const { finished } = defineProps({
  finished: {
    type: Boolean,
    default: false,
  },
});

const loading = defineModel<boolean>('loading');
const emit = defineEmits(['load']);

const targetRef = useTemplateRef('target');
const targetIsVisible = useElementVisibility(targetRef);

const load = () => {
  loading.value = true;
  emit('load');
}

onMounted(() => {
  const { pause, resume } = watchPausable(
    targetIsVisible,
    () => {
      if (!finished && !loading.value && targetIsVisible.value) {
        pause();
        load();
      }
    },
    { immediate: true },
  );

  watch(
    loading,
    (newValue, oldValue) => {
      if (oldValue === true && newValue === false && !finished) {
        setTimeout(() => {
          if (targetIsVisible.value) {
            load();
          }
          else {
            resume();
          }
        }, 50);
      }
    },
  );
});
</script>

<template>
  <ul class="component-infinite-scroll">
    <slot></slot>
    <li class="flex-x-center color-gray-1" ref="target" v-if="!finished">
      <div class="i-svg-spinners-3-dots-scale size-32" v-if="loading"></div>
    </li>
  </ul>
</template>

<style lang="scss" scoped>
</style>
